﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace IdCard
{
    public class CommandSender
    {
        public static byte[] SerialCommandSend(string PortName, byte[] command)
        {
            // 配置串口参数
            SerialPort serialPort = new SerialPort(
                portName: PortName,       // 串口号
                baudRate: 9600,         // 波特率
                parity: Parity.None,    // 校验位
                dataBits: 8,            // 数据位
                stopBits: StopBits.One  // 停止位
            );

            try
            {
                serialPort.Open();
                Console.WriteLine("串口已连接");

                // 示例命令（十六进制格式）
                //byte[] command = { 0x01, 0x06, 0x00, 0x01, 0x00, 0x03, 0x0A, 0x0B };

                serialPort.Write(command, 0, command.Length);
                Console.WriteLine("命令已发送");

                // 可选：接收响应（假设有返回）
                Thread.Sleep(200); // 等待设备响应
                int bytesToRead = serialPort.BytesToRead;
                byte[] buffer = new byte[bytesToRead];
                serialPort.Read(buffer, 0, bytesToRead);
                //Console.WriteLine($"收到响应：{BitConverter.ToString(buffer)}");
                return buffer;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"错误：{ex.Message}");
                return null;
            }
            finally
            {
                if (serialPort.IsOpen)
                    serialPort.Close();
                
            }
        }

      public static byte[] SendTcpCommand(string ip, int port, byte[] command)
        {
            try
            {
                using (TcpClient client = new TcpClient(ip, port))
                using (NetworkStream stream = client.GetStream())
                {
                    // 发送命令
                    stream.Write(command, 0, command.Length);
                    //Console.WriteLine($"已发送命令: {BitConverter.ToString(command)}");

                    // 接收响应（动态调整缓冲区大小）
                    byte[] buffer = new byte[1024]; // 初始缓冲区
                    int bytesRead = stream.Read(buffer, 0, buffer.Length);

                    // 返回实际接收到的字节（去除多余空字节）
                    byte[] response = new byte[bytesRead];
                    Array.Copy(buffer, response, bytesRead);
                    return response;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"通信错误: {ex.Message}");
                return null; // 或抛出异常 throw;
            }
        }

    }
}
